﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class Utils
{
    /// <summary>
    /// 将字符Base64编码
    /// </summary>
    public static string ToBase64(string str)
    {
        if (str == null)
        {
            return string.Empty;
        }
        return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(str));
    }

    /// <summary>
    /// 将字符Base64解码
    /// </summary>
    public static string FromBase64(string base64_str)
    {
        if (base64_str == null)
        {
            return string.Empty;
        }
        return System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(base64_str));
    }

    /// <summary>
    /// 获取Utf-8 字符串的字节数组
    /// </summary>
    public static byte[] GetBytes(string str)
    {
        return System.Text.Encoding.UTF8.GetBytes(str);
    }

    public static string GetInSqlChar(string str)
    {
        if (string.IsNullOrEmpty(str))
        {
            return " ('') ";
        }
        StringBuilder sb = new StringBuilder();
        for (int j = 0; j < str.Length; j++)
        {
            string ch = str[j].ToString();
            if (ch.Contains("'"))
            {
                continue;
            }
            ch = "'" + ch + "'";
            string douhao = ",";
            if (j == str.Length - 1)
            {
                douhao = string.Empty;
            }
            sb.Append(ch + douhao);
        }
        string insql = sb.ToString();
        insql = " (" + insql + ") ";
        return insql;
    }

    /// <summary>
    /// 对象类型转换
    /// </summary>
    /// <typeparam name="TResult">返回类型</typeparam>
    /// <param name="obj">对象</param>
    /// <returns></returns>
    public static TResult ConvertTo<TResult>(object obj)
    {
        Type type = typeof(TResult);
        type = Nullable.GetUnderlyingType(type) ?? type;
        if (type != null)
        {
            object result = null;
            if (type.IsEnum)
            {
                result = Enum.Parse(type, obj.ToString(), true);
            }
            else if (type.IsAssignableFrom(typeof(Guid)))
            {
                result = Guid.Parse(obj.ToString());
            }

            if (result != null)
            {
                return (TResult)result;
            }
        }
        return (TResult)Convert.ChangeType(obj, type);
    }

    /// <summary>
    /// 对象类型转换，转换失败，返回默认值
    /// </summary>
    /// <typeparam name="TResult">返回类型</typeparam>
    /// <param name="obj">对象</param>
    /// <param name="def">默认值</param>
    /// <returns></returns>
    public static TResult ConvertTo<TResult>(object obj, TResult def)
    {
        try
        {
            if (obj == null)
            {
                return def;
            }
            return ConvertTo<TResult>(obj);
        }
        catch
        {
            return def;
        }
    }

}